<?php

/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
defined('_HEXEC') or die('Restricted access!');

//导入引用文件
HClass::import('service.baseservice');

/**
 * 商品 服务层
 *
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @since 1.0.0
 */
class GoodsService extends BaseService
{

    /**
     * 促销对象
     * @var
     */
    private $_couxiao;

    /**
     * sku对象
     * @var
     */
    private $_sku;

    /**
     * skugoods 对象
     * @var
     */
    private $_skuGoods;

    /**
     * goods 对象
     * @var
     */
    private $_goods;

    /**
     * 构造函数
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     */
    public function __construct()
    {
        parent::__construct();
        $this->_couxiao     = HClass::quickLoadModel('couxiao');
        $this->_sku         = HClass::quickLoadModel('sku');
        $this->_skuGoods    = HClass::quickLoadModel('skugoods');
        $this->_goods       = HClass::quickLoadModel('goods');
    }

    /**
     * 更新商品最高、最低价
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access public
     * @param $goodsId 商品编号
     */
    public function updateGoodsMinMaxPrice($goodsId, $type = null)
    {
        $type           = !$type ? $this->_getGoodsCouXiaoType($goodsId) : intval($type);
        $field          = 'price';
        $where          = '`goods_id` = ' . $goodsId;
        switch($type) {
            case 1: $field = 'cheap_price'; break;
            case 3: $field = 'chengben_price'; break;
            case 4: $field = 'miaosha_price'; break;
            case 5: $field = 'choujiang_price';break;
            case 6: $field = 'tuan_price'; break;
            case 2:
            case 0:
            default: $field = 'price'; break;
        }
        $minPrice       = $this->_skuGoods->getMinPrice($field, $where);
        $maxPrice       = $this->_skuGoods->getMaxPrice($field, $where);
        $minVipPrice    = $this->_skuGoods->getMinPrice('vip_price', $where);
        $maxVipPrice    = $this->_skuGoods->getMaxPrice('vip_price', $where);
        $data           = array(
            'min_price' => $minPrice,
            'max_price' => $maxPrice,
            'min_vip_price' => $minVipPrice,
            'max_vip_price' => $maxVipPrice
        );
        $this->_goods->editByWhere($data, '`id` = ' . $goodsId);
    }

    /**
     * 得到商品促销类别
     *
     */
    public function getGoodsCouXiaoType($goodsId)
    {
        $type   = $this->_getGoodsCouXiaoType($goodsId);

        return $type ? $type : 2;
    }

    /**
     * 得到商品促销类别
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @access private
     * @param $goodsId 商品编号
     */
    private function _getGoodsCouXiaoType($goodsId)
    {
        $where              = '`parent_id` = ' . $goodsId . ' AND `status` = 2';
        $record             = $this->_couxiao->getRecordByWhere($where);
        if(!$record) {
            return 0;
        }
        $type               = intval($record['type']);
        $time               = $_SERVER['REQUEST_TIME'] ? $_SERVER['REQUEST_TIME'] : time();
        if($time < $record['start_time']) {
            return 0;
        }
        if($time > $record['end_time']) {
            return 0;
        }

        return $type;
    }

    /**
     * 获取商品记录的实际价格
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $id 商品id
     * @params $groupId 商品属性规格组合
     * @params $number 购买数量
     * @params $buyType 购买方式 2 直接购买 3 拼团购买 4 单独购买
     * @access public
     */
    public function getRecordPrice($id, $groupId, $number = 0, $buyType = 2)
    {
        return $this->_getRecordPrice($id, $groupId, $number, $buyType);
    }

    /**
     * 获取商品需要支付的实际价格
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $id 商品id
     * @params $groupId 商品属性规格组合
     * @params $number 购买数量
     * @params $buyType 购买方式 2 直接购买 3 拼团购买 4 单独购买
     * @access public
     */
    public function getPaymentPrice($id, $groupId, $number = 0, $buyType = 2)
    {
        return $this->_getRecordPrice($id, $groupId, $number, $buyType, true);
    }

    /**
     * 获取商品列表的实际价格
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $list 列表 如 array(array('goods_id' => 1, 'group_id' => ':1:2:', 'number' => 2))
     * @params $buyType 购买方式 2 直接购买 3 拼团购买 4 单独购买
     * @access public
     */
    public function getListPrice($list, $isPayment = false)
    {
        foreach($list as &$item) {
            $item['price'] = $this->_getRecordPrice(
                $item['goods_id'], $item['group_id'], $item['number'], $item['buy_type'], $isPayment
            );
        }

        return $list;
    }

    /**
     * 获取商品记录的实际价格
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $id 商品id
     * @params $groupId 商品属性规格组合
     * @params $number 购买数量
     * @params $buyType 购买方式 2 直接购买 3 拼团购买 4 单独购买
     * @access protected
     */
    protected function _getRecordPrice($id, $groupId, $number = 0, $buyType = 2, $isPayment = false)
    {
        $where 			= '`status` = 2 AND `parent_id` = ' . $id 
            . ' AND `start_time` < ' . time() 
            . ' AND `end_time` > ' . time();
        $record 		= $this->_couxiao->getRecordByWhere($where);
        $skuRecord 		= $this->_sku->getRecordByWhere('`code` = \'' . $groupId . '\'');
        $skuGoodsWhere 	= '`goods_id` = ' . $id 
            . ' AND `sku_id` = ' . $skuRecord['id'];
        $skuGoodsRecord = $this->_skuGoods->getRecordByWhere($skuGoodsWhere);
        if(!$record){
            return $this->_getUserPrice($skuGoodsRecord, $isPayment);
        }
        $price 			= $this->_getUserPrice($skuGoodsRecord, $isPayment);
        switch ($record['type']) {
            case 1:
                $price 	= $skuGoodsRecord['cheap_price'];
                break;
            case 3:
                if($number >= $record['number']){
                    $price 	= $skuGoodsRecord['chengben_price'];
                }
                break;
            case 4:
                $price 	= $skuGoodsRecord['miaosha_price'];
                break;
            case 5:
                $price  = $skuGoodsRecord['choujiang_price'];
                break;
            case 6:
                if($buyType != 4){
                    $price  = $skuGoodsRecord['tuan_price'];
                }
                break;
            case 2:
            default: break;
        }

        return $price;
    }

    /**
     * 得到用户会员、VIP价格
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $skuGoodsRecord SKUGoods数据组
     * @params $isPayment 是否为支付价
     * @access private
     */
    private function _getUserPrice($skuGoodsRecord, $isPayment)
    {
        if(false === $isPayment) {
            return $skuGoodsRecord['price'];
        }
        if(false === HObject::GC('OPEN_VIP_PRICE')) {
            return $skuGoodsRecord['price'];
        }

        return 'member-vip' === HSession::getAttribute('actor', 'user') 
            ? $skuGoodsRecord['vip_price'] : $skuGoodsRecord['price'];
    }

    /**
     * 获取商品列表及其活动
     *
     * @author xjiujiu <xjiujiu@foxmail.com>
     * @params $list 列表 如 array(array())
     * @access public
     */
    public function formatListWithCouxiao($list)
    {
        if(!$list){
            return $list;
        }
        $where      = '`status` = 2 '
            . ' AND ((`start_time` < ' . $_SERVER['REQUEST_TIME']
            . ' AND `end_time` > ' . $_SERVER['REQUEST_TIME']  . ')'
            . ' OR (`end_time` > ' .  $_SERVER['REQUEST_TIME']
            . ' AND `type` = 4)) '
            . ' AND (' . HSqlHelper::whereInByListMap('parent_id', 'id', $list) . ')';
        $couxiaoList    = $this->_couxiao->getAllRowsByFields('`id`, `parent_id`, `type`, `number`', $where);
        $couxiaoMap     = HArray::turnItemValueAsKey($couxiaoList, 'parent_id');
        foreach($list as &$item){
            $item['couxiao'] = $couxiaoMap[$item['id']];
        }

        return $list;
    }

}